package org.helgoboss.file_manager_commandlet

import org.helgoboss.commandlet._
import java.io.File
import org.helgoboss.file_manager.FileManager
import org.helgoboss.launchlet.{LaunchletExecutionContext, Launchlet}


class FileManagerCommandlet(fileManager: FileManager) extends Commandlet with Launchlet {
	val id = "org.helgoboss.file-manager"
    
    val name = "File Manager"
    
	def execute(context: ExecutionContext) = {
        openFileManager(context.arguments, Some(context.workingDirectory))
	}

    private def openFileManager(arguments: Seq[String], workingDirectory: Option[File]) = {
        def convertToAbsoluteDir(path: Option[String]) = {
            path orElse Some(".") match {
                case Some(p) =>
                    val f = new File(p)
                    val absoluteFile = if (f.isAbsolute) f else new File(workingDirectory.get, p)
                    Some(if (absoluteFile.isDirectory) absoluteFile else absoluteFile.getParentFile)

                case None => None
            }
        }
        fileManager.open(
                leftDir = convertToAbsoluteDir(arguments.lift(0)),
                rightDir = convertToAbsoluteDir(arguments.lift(1))
        )
        0
    }
    
	def execute(context: LaunchletExecutionContext) = {
        openFileManager(context.arguments, context.workingDirectory)
	}
    
    
}